<?php

class Setup_ProfileController extends Ext_Controller_Action_Front
{
    public function init()
    {
        parent::init();
    }

    public function preDispatch()
    {
        parent::preDispatch();
        
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        if(!$userId){
            return "";
        }

        $roleId = Ext_User::getInstance()->show($userId)->buildRole()->role->roleId;
        $acl = Ext_Acl::getInstance()->build($roleId);
        if(!$acl->isAllowed($roleId, 'setup', 'profile')){
            $this->_forward("show-access-denied", "auth", "account");
        }
    }
    
    public function savePostAction()
    {
        $viewResult = new Ext_View_Result();

        $nickname    = $this->filter->filter($this->_request->getPost('nickname'));
        $description = $this->filter->filter($this->_request->getPost('description'));

        $validater = new Ext_Validate();
        $validater->addValidater(new Add_Validate_Setup_Profile_SavePost_Nickname($nickname));
        $validater->addValidater(new Add_Validate_Setup_Profile_SavePost_Description($description));
        if(!$validater->isValid()){
            $viewResult->addMessages($validater->getMessages());
            $viewResult->setNoRender();
            return "";
        }

        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        
        $row = array (
            'nickname' => $nickname,
        );
        App_Model_DbTable_User::getInstance()->addOld($row, $userId);
        
        $userDescriptionOne = App_Model_DbTable_User_Description::getInstance()->getRowByUserId($userId);
        if(!$userDescriptionOne){
            $row = array (
                'userId'      => $userId,
                'description' => $description,
            );
            App_Model_DbTable_User_Description::getInstance()->addNew($row);
        }else{
            $row = array (
                'description' => $description,
            );
            App_Model_DbTable_User_Description::getInstance()->addOld($row, $userId);
        }
        
        $viewResult->addMessages($this->translater->_("Submit success."));
        $viewResult->setResult(1);
        $viewResult->setNoRender();
    }

    public function showFormAction()
    {
        $userId = Ext_Auth_Front::getInstance()->getIdentity();

        $viewForm = new Ext_View_Form_Setup_Profile();
        
        $userOne = App_Model_DbTable_User::getInstance()->getRowById($userId);
        if(isset($userOne['nickname']))
        {
            $viewForm->getElement('nickname')->setValue($userOne['nickname']);
        }
        
        $userDescriptionOne = App_Model_DbTable_User_Description::getInstance()->getRowByUserId($userId);
        if(isset($userDescriptionOne['description']))
        {
            $viewForm->getElement('description')->setValue($userDescriptionOne['description']);
        }
        
        $this->view->form = $viewForm;
    }
    
}

?>